
package cloud.xlh.service.impl;

import cloud.xlh.infrastructure.utils.StringUtil;
import cloud.xlh.service.TokenService;
import cloud.xlh.utils.RestTemplateUtil;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Service;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : xlh_osms
 * @ Author: XuLeHuang
 * @ Date: 2022/5/27 16:24
 * @ Description:
 */

@Service
public class TokenServiceImpl implements TokenService {
    @Autowired
    private RestTemplateUtil restTemplateUtil;
    @Value("${auth-address}")
    private String authAddress;

    /**
     * 获取请求token
     */
    @Override
    public String getToken(ServerHttpRequest request) {
        String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        if (!StringUtil.isEmpty(token) && token.startsWith("Bearer ")) {
            token = token.replace("Bearer ", "");
        }
        return token;
    }


    /**
     * 标注了@Idempotent注解的方法，请求的时候就会到这里
     */

    /**
     * 校验token
     */
    public boolean checkToken(String token) {
        /**
         * 远程调用认证中心进行token的校验
         * */
        JSONObject body = new JSONObject();
        body.put("token" , token);
        Boolean passed = restTemplateUtil.postForObject(authAddress , body , null , null , Boolean.class, MediaType.APPLICATION_JSON_VALUE);
        return passed;
    }
}

